package com.tjetc.factory2;

import com.tjetc.factory.IResourceLoader;
import com.tjetc.simplefactory.Resource;
import com.tjetc.simplefactory.ResourceLoadException;

import java.io.InputStream;
import java.util.*;

/**
 * 加载器
 */
public class ResourceLoader {
    private static Map<String, IResourceLoader1> resourceLoaderCache = new HashMap<>(8);

    static {
        InputStream inputStream = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("resourceloader1.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            Set<Map.Entry<Object, Object>> entries = properties.entrySet();
            for (Map.Entry<Object, Object> entry : entries) {
                // key： http value：是对应的工厂
                String key = entry.getKey().toString();
                // 根据类路径找到类
                Class<?> aClass = Class.forName(entry.getValue().toString());
                // 根据构造器创建对象
                // 此时的对象就是对应的工厂实例
                IResourceLoader1 resourceLoader = (IResourceLoader1) aClass.getConstructor().newInstance();
                resourceLoaderCache.put(key, resourceLoader);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据路径返回资源
     * file:// classpath:// http:// https://
     *
     * @param path
     * @return
     */
    public AbstractResource load(String path) {
        // 1.根据路径获取前缀
        String type = getPrefix(path);
        return resourceLoaderCache.get(type).load(path);
    }

    // 根据路径获取前缀
    private String getPrefix(String path) {
        if (Objects.isNull(path) || !path.contains(":") || Objects.equals("path", "")) {
            throw new ResourceLoadException();
        }
        String[] split = path.split(":");
        return split[0];
    }
}
